import { api } from "@/api";
import { useMyContext } from "@/hooks";
import action from "@/store/action";
import { convertImgUrl } from "@/utils/MyFun";
import { Icon } from "@iconify/react";
import { Avatar, Button } from "antd";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";

const Styled = styled.div`
  margin-bottom: 5rem;
  padding: 2.5rem;
  border-style: solid;
  border-radius: 1rem;
  border-color: rgba(144, 147, 153, 1);
  border-width: 1px;
  display: flex;
  .area {
    margin-left: 3rem;
    width: 100%;
    margin-top: 1.25rem;
    margin-bottom: 1.25rem;
    textarea {
      background: url(https://static.talkxj.com/config/commentBack.webp) 100%
        100% no-repeat;
      resize: none;
      font-size: 4rem;
      width: 100%;
    }
    .sub {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
`;

const CommentField = ({ show, type, topicId, afterSubmit }, ref) => {
  const dispatch = useDispatch();
  const { messageApi } = useMyContext();
  const { appStore, userStore } = useSelector((state) => {
    return {
      appStore: state.app,
      userStore: state.user,
    };
  });

  let [isShow, setIsShow] = useState(show); // 是否显示
  const [data, setData] = useState({
    nickname: "", // * 回复用户, 不为空则说明是回复框
    content: "", // 回复内容
    topic_id: topicId ?? 0, // 主题 id
    reply_user_id: 0, // 回复用户 id
    parent_id: 0, // 父评论 id
    type: type,
  });

  //判断是回复还是评论， 存在nickname则是回复
  const isReply = useMemo(() => {
    return !!data.nickname;
  }, [data.nickname]);

  // 取消评论
  function setReply(flag) {
    setIsShow(flag);
  }
  // TODO: 表情框
  function chooseEmoji() {
    messageApi.info("表情选择正在开发中...");
  }
  // 输入框提示语
  const placeholderText = useMemo(
    () => (data.nickname ? `回复 @${data.nickname}：` : "留下点什么吧..."),
    [data.nickname]
  );
  //提交评论
  const submitComment = async () => {
    //验证是否登录
    if (!userStore.userInfo.id) {
      dispatch(action.app.setLoginFlag(true));
      return;
    }

    // 验证通过判断不能为空
    if (!data.content.trim()) {
      messageApi.error("评论内容不能为空");
      return;
    }

    //
    try {
      await api.saveComment(data);
      messageApi.info("评论成功");
      //重置表单内容
      setData({
        ...data,
        content: "",
      });
      isReply && setReply(false);
      await afterSubmit(); //父组件刷新获取数据
    } catch (error) {}
  };

  useImperativeHandle(ref, () => {
    return { data, setReply, setData };
  });

  return (
    <>
      {isShow ? (
        <Styled>
          <Avatar size={36} src={convertImgUrl(userStore.userInfo.avatar)} />
          <div className="area">
            <textarea
              rows="5"
              placeholder={placeholderText}
              onChange={(e) => {
                setData({
                  ...data,
                  content: e.target.value,
                });
              }}
            ></textarea>
            <div className="sub">
              <Icon
                fontSize={24}
                icon="mingcute:happy-fill"
                color="orange"
                onClick={chooseEmoji}
              />
              <div className="flex">
                {data.nickname ? (
                  <Button
                    type="primary"
                    danger
                    onClick={setReply.bind(null, false)}
                  >
                    取消
                  </Button>
                ) : null}
                <Button type="primary" onClick={submitComment}>
                  提交
                </Button>
              </div>
            </div>
          </div>
        </Styled>
      ) : (
        <></>
      )}
    </>
  );
};

export default forwardRef(CommentField);
